package com.onluy.frameworkcloud.system.resolver;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.onluy.frameworkcloud.data.bean.Pagination;

public class PaginationMethodArgumentResolver extends BaseMethodArgumentResolver
  implements HandlerMethodArgumentResolver
{
  protected Logger log =   LoggerFactory.getLogger(this.getClass());
  private static final int DEFAULT_PAGE_SIZE = 10;
  private static final int DEFAULT_CURR_PAGE = 1;

  public boolean supportsParameter(MethodParameter parameter)
  {
    return Pagination.class.isAssignableFrom(parameter.getParameterType());
  }

  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
    throws Exception
  {
    String actionType = webRequest.getParameter("__actionType");
    if ("export".equals(actionType))
      return new Pagination(true);
    if ("expand".equals(actionType)) {
      return null;
    }

    String rows = webRequest.getParameter("rows");
    String page = webRequest.getParameter("page");
    int pageSize = StringUtils.isEmpty(rows) ? 10 : Integer.parseInt(rows);
    int currPage = StringUtils.isEmpty(page) ? 1 : Integer.parseInt(page);
    int start = (currPage - 1) * pageSize;
    start = start < 0 ? 0 : start;
    Pagination pagination = new Pagination();
    pagination.setRange(start, pageSize);
    pagination.setCurrPage(currPage);
    log.info(" >>>>>>>>>>>>>>>>>>>> PaginationMethodArgumentResolver.pagination : "+ JSON.toJSONString(pagination));
    return pagination;
  }
}